package com.example.spring.job;

import com.example.autojob.logging.model.producer.AutoJobLogHelper;
import com.example.autojob.skeleton.framework.mail.IMailClient;
import com.example.autojob.skeleton.framework.task.AutoJobRunningContext;
import com.example.autojob.skeleton.framework.task.AutoJobRunningContextHolder;
import com.example.autojob.skeleton.framework.task.AutoJobRunningStack;
import com.example.autojob.skeleton.framework.task.RunningStackEntry;
import com.example.autojob.util.convert.DateUtils;
import com.example.autojob.util.thread.SyncHelper;
import com.example.spring.mapper.TestMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 测试任务
 *
 * @Author Huang Yongxiang
 * @Date 2022/11/02 9:53
 * @Email 1158055613@qq.com
 */
@Slf4j
@Component
public class Jobs {
    @Autowired(required = false)
    private TestMapper mapper;

    //@AutoJob(attributes = "{'hello autoJob'}", defaultStartTime = StartTime.NOW, cycle = 3, asType = AutoJobTask.TaskType.DB_TASK, repeatTimes = 3, childTasksId = "1")
    public void hello(String str) {
        //获取当前的上下文
        Random random = new Random();
        int flag = random.nextInt(100) + 1;
        AutoJobRunningContext context = AutoJobRunningContextHolder.currentTaskContext();
        AutoJobLogHelper logHelper = context.getLogHelper();
        logHelper.setSlf4jProxy(log);
        logHelper.info("参数：{}", str);
        logHelper.info("本次执行上下文参数：{}", flag);
        logHelper.info("当前调度记录ID：{}", context.getSchedulingRecordID());
        logHelper.info("当前任务ID：{}", context.getTaskId());
        logHelper.info("本次调度启动时间：{}", DateUtils.formatDateTime(new Date(context.getStartTime())));
        logHelper.info("当前任务类型：{}", context
                .getTaskType()
                .toString());
        //获取当前任务运行栈
        AutoJobRunningStack stack = context.getCurrentStack();
        logHelper.info("当前栈深：{}", stack.depth());
        //获取本次运行的栈帧
        RunningStackEntry current = stack.currentStackEntry();
        //添加本次运行的一下上下文参数，以便本次执行失败重试能直接恢复
        current.addParam("runningPos", flag);
        //也可以获取上次执行的上下文参数
        Optional<RunningStackEntry> last = stack.lastStackEntry();
        last.ifPresent(stackEntry -> logHelper.info("上次执行上下文参数{}", stackEntry.getParam("runningPos")));
        last.ifPresent(stackEntry -> logHelper.info("上次是否执行成功：{}", stackEntry.isSuccess()));
        last.ifPresent(stackEntry -> logHelper.info("上次执行参数：{}", stackEntry.getArgs()));
        //获取当前任务具有的邮件客户端
        IMailClient mailClient = context.getMailClient();

        if (flag % 3 == 0) {
            throw new RuntimeException("模拟异常发生");
        }
    }

    //@AutoJob(id = 1, schedulingStrategy = SchedulingStrategy.AS_CHILD_TASK, asType = AutoJobTask.TaskType.DB_TASK)
    public void longTask() {
        AutoJobLogHelper logHelper = AutoJobLogHelper.getInstance();
        logHelper.setSlf4jProxy(log);
        logHelper.info("long task start");
        SyncHelper.sleepQuietly(10, TimeUnit.SECONDS);
        logHelper.info("long task end");
    }

    //@AutoJob(defaultStartTime = StartTime.NOW, repeatTimes = -1, cycle = 10, asType = AutoJobTask.TaskType.DB_TASK)
    public void childTask() {
        AutoJobLogHelper logHelper = AutoJobLogHelper.getInstance();
        logHelper.setSlf4jProxy(log);
        logHelper.info("child task start");
        SyncHelper.sleepQuietly(3, TimeUnit.SECONDS);
        logHelper.info("child task end");
    }

    //@AutoJob(alias = "获取随机字符串", cronExpression = "* * 0/5 17 * * ?", repeatTimes = -1, childTasksId = "3")
    //public String getRandomString() {
    //    return StringUtils.getRandomStr(16);
    //}

    //@AutoJob(defaultStartTime = StartTime.NOW, repeatTimes = -1, cycle = 12, asType = AutoJobTask.TaskType.DB_TASK)
    public void error() {
        String str = null;
        str.length();
    }

    //@AutoJob(id = 5, defaultStartTime = StartTime.NOW, methodObjectFactory = SpringMethodObjectFactory.class)
    public void mapperTest() {
        AutoJobLogHelper logHelper = AutoJobLogHelper.getInstance();
        logHelper.info("mapper = {}", mapper);
        if (mapper != null) {
            logHelper.info("count = {}", mapper.count());
        }
    }

    //@FactoryAutoJob(NeedDaemonTaskFactory.class)
    public void needDaemon() {
        AutoJobLogHelper logHelper = AutoJobLogHelper.getInstance();
        int i = 0;
        while (true) {
            SyncHelper.sleepQuietly(1, TimeUnit.SECONDS);
            i++;
            if (i % 10 == 0) {
                throw new RuntimeException("模拟异常退出");
            }
        }
    }


    //@FactoryAutoJob(WithMailConfigTaskFactory.class)
    public long sendMail(String title, String body) {
        IMailClient client = AutoJobRunningContextHolder
                .currentTaskContext()
                .getMailClient();
        if (client != null) {
            client.sendMail(title, body);
        } else {
            AutoJobLogHelper
                    .getInstance()
                    .error("邮件客户端不存在");
        }
        return AutoJobRunningContextHolder
                .currentTaskContext()
                .getStartTime();
    }


}
